package com.bupt.basic;
import java.util.LinkedList;
public class ProducerConsumer {
	public static void main(String args[]) {
		//苹果箱
		AppleCase appleCase = new AppleCase();
		//取苹果的对象
		FetchMan fetchMan = new FetchMan(appleCase);
		//放苹果的对象
		PutAppleMan putAppleMan = new PutAppleMan(appleCase);
		putAppleMan.start();
		fetchMan.start();
	}
}
//苹果类
class Apple {
}
/**
 * 容器类
 * @author Frank
 *
 */
class AppleCase {
	// 苹果箱最大容量
	private final int case_size = 5;
	// 苹果箱存储list
	private LinkedList<Apple> list = new LinkedList<Apple>();

	// 放入苹果操作,每次放入一个苹果；
	public void putApple() {
		// 同步代码段
		synchronized (list) {
			// 如果仓库剩余容量不足
			while (list.size() > case_size) {
				System.out.println("箱子已经满了，不能继续放入苹果！");
				try {
					// 由于条件不满足，放入过程阻塞
					list.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			list.add(new Apple());
			System.out.println("成功放入一个苹果！单独给钱苹果箱中的苹果数为" + list.size());
			list.notifyAll();
		}
	}

	public void fetchApple() {
		// 同步代码段
		synchronized (list) {
			// 如果苹果箱中没有苹果
			while (list.size() < 1) {
				System.out.println("苹果箱中没有苹果，请稍后再取！");
				try {
					// 线程阻塞
					list.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			list.remove();
			System.out.println("成功取走一个苹果！目前苹果箱中容量为" + list.size());
			list.notifyAll();
		}
	}
	public LinkedList<Apple> getList() {
		return list;
	}

	public void setList(LinkedList<Apple> list) {
		this.list = list;
	}

	public int getCase_size() {
		return case_size;
	}
}

class PutAppleMan extends Thread {
	// 苹果箱
	private AppleCase appleCase;

	// 构造函数
	public PutAppleMan(AppleCase appleCase) {
		this.appleCase = appleCase;
	}

	public void run() {
		fetchApple();
	}

	// 取走苹果
	private void fetchApple() {
		appleCase.fetchApple();
	}

	public AppleCase getAppleCase() {
		return appleCase;
	}

	public void setAppleCase(AppleCase appleCase) {
		this.appleCase = appleCase;
	}
}

class FetchMan extends Thread {
	// 苹果箱
	private AppleCase appleCase;

	// 构造函数，设置仓库
	public FetchMan(AppleCase appleCase) {
		this.appleCase = appleCase;
	}

	// 线程run函数
	public void run() {
		fetch();
	}

	// 调用仓库Storage的生产函数
	public void fetch() {
		appleCase.fetchApple();
	}

	public AppleCase getAppleCase() {
		return appleCase;
	}

	public void setAppleCase(AppleCase appleCase) {
		this.appleCase = appleCase;
	}
}
